package cn.itcast.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * TODO
 *
 * @Author mr.Css
 * @Date 2025-01-03 15:47
 */
@Order(-1)// 数字越小，优先级越高
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        // 2.获取返回参数
        ServerHttpResponse response = exchange.getResponse();
        // 3.判断是否有authorization参数
        String authorization = queryParams.getFirst("authorization");
        if (!"admin".equals(authorization)) {
            // 4.校验不通过，返回403
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        // 5.校验通过，放行
        return chain.filter(exchange);
//        return null;
    }
}
